package csc.daonjpa.java.controller;

import java.util.List;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.domain.TargetAccount;
import csc.daonjpa.java.service.BankService;

@Controller
public class CustomerController {

	private static final Logger LOG = Logger
			.getLogger(CustomerController.class);
	private BankService bankService;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}

	/**
	 * Go to change customer info form
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/goChangeInfo")
	public ModelAndView goChangeInfo(Model model) {
		return new ModelAndView("changeInfo");
	}

	/**
	 * Change customer's information
	 */
	@RequestMapping(value = "/changeInfoAction", method = RequestMethod.POST)
	public ModelAndView updateCustomerInfo(HttpServletRequest request,
			Model model) {
		// Change password
		ModelAndView modelAndView = null;
		Customer currentCustomer = (Customer) request.getSession()
				.getAttribute("currentCustomer");
		String loginid = currentCustomer.getLoginid();
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");

		// Have to set the session's currentUser attribute to update customer's
		// info in all pages
		Customer customer = new Customer(loginid, "", firstName, lastName,
				address, phone);
		customer.setPassword(currentCustomer.getPassword());
		customer.setAccounts(currentCustomer.getAccounts());
		customer.setCards(currentCustomer.getCards());

		if (bankService.updateCustomerInfo(customer) == 1) {
			request.setAttribute(
					"successMessage",
					"Update customer's information successfully! To see your updated customer info, please go to 'Customer Info' section.");
			request.getSession().setAttribute("currentCustomer", customer);
			modelAndView = new ModelAndView("home");
		} else {
			request.setAttribute("errorMessage",
					"Can not update customer's information!");
			modelAndView = new ModelAndView("changeInfo");
		}

		return modelAndView;
	}

	/**
	 * Go to change password form
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/goChangePassword")
	public ModelAndView goChangePassword(Model model) {
		return new ModelAndView("changePassword");
	}

	/**
	 * Change user password
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/changePasswordAction", method = RequestMethod.POST)
	public ModelAndView changePassword(HttpServletRequest request, Model model) {

		// Change password
		ModelAndView modelAndView = null;
		Customer currentCustomer = (Customer) request.getSession()
				.getAttribute("currentCustomer");
		String loginid = currentCustomer.getLoginid();
		String newPassword = request.getParameter("newPass");
		String oldPassword = request.getParameter("oldPass");
		String confirmPassword = request.getParameter("confirmNewPass");
		String password = currentCustomer.getPassword();

		if (!password.equals(oldPassword)) {
			request.setAttribute("errorMessage",
					"Your old password is not correct!");
			modelAndView = new ModelAndView("changePassword");
		} else if (!newPassword.equals(confirmPassword)) {
			request.setAttribute("errorMessage",
					"Your new password and Your confirm new password is not matched!");
			modelAndView = new ModelAndView("changePassword");
		} else {
			// Every input is valid: NewPass == ConfirmPass
			if (bankService.changeCustomerPassword(loginid, newPassword) == 1) {
				request.setAttribute("successMessage",
						"Changed customer password successfully!");
				currentCustomer.setPassword(newPassword);
				request.getSession().setAttribute("currentCustomer",
						currentCustomer);
				modelAndView = new ModelAndView("changePassword");
			} else {
				request.setAttribute("errorMessage", "Can not change password!");
				modelAndView = new ModelAndView("changePassword");
			}
		}

		return modelAndView;
	}

	@RequestMapping(value = "/getCustomerAccounts")
	public ModelAndView getAccounts(HttpServletRequest request, Model model) {

		// Read customer info from request and save into customer object
		String id = request.getParameter("hiddenId");
		ModelAndView modelAndView = null;
		List<Account> accounts = null;

		accounts = bankService.getAccountsByCustomerId(id);
		modelAndView = new ModelAndView("customerAccounts");

		if (modelAndView != null) {
			modelAndView.addObject("accounts", accounts);
		}
		return modelAndView;
	}

	/**
	 * Adds customer to DB
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/createCustomer")
	public ModelAndView addCustomer(HttpServletRequest request, Model model) {
		// Read customer info from request and save into customer object
		String loginid = request.getParameter("loginid");
		String password = request.getParameter("password");
		String firstname = request.getParameter("firstname");
		String lastname = request.getParameter("lastname");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");

		Customer customer = new Customer(loginid, password, firstname,
				lastname, address, phone);

		ModelAndView modelAndView = new ModelAndView("customerList");
		try {
			// Save customer to DB
			if (bankService.addCustomer(customer)) {
				model.addAttribute("successMessage",
						"Create customer succesfully!");
			} else {
				model.addAttribute("errorMessage", "Duplicated customer found!");
			}
		} catch (PersistenceException ex) {
			if (ex.getCause() instanceof ConstraintViolationException) {
				model.addAttribute("errorMessage", "Duplicated customer found!");
			} else {
				model.addAttribute("errorMessage", "Error adding new customer!");
			}
			LOG.error("Error found adding an customer", ex);
			throw ex;
		} catch (Exception e) {
			LOG.error("General Error found adding an customer", e);
			throw e;
		}

		return modelAndView;
	}

	@RequestMapping(value = "/listCustomer")
	public ModelAndView getCustomerList(Model model) {

		// Get the list of all customer from DB
		List<Customer> customers = bankService.getCustomers();

		ModelAndView modelAndView = new ModelAndView("customerList");
		modelAndView.addObject("customers", customers);
		return modelAndView;
	}

	/**
	 * Go to log in form
	 */
	@RequestMapping(value = "/goLogIn")
	public ModelAndView gotoLogin(Model model) {
		return new ModelAndView("goLogIn");
	}

	/**
	 * Log in Customer
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/logInCustomer", method = RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request, Model model) {

		ModelAndView modelAndView = null;
		String custId = request.getParameter("custId");
		String password = request.getParameter("password");

		Customer customer = bankService
				.getCustomerByLoginInfo(custId, password);
		if (customer != null) {
			modelAndView = new ModelAndView("home");
			request.getSession().setAttribute("currentCustomer", customer);

			// Set a session's attribute for all the target account in the db
			List<TargetAccount> tarAccounts = bankService
					.getAllTargetAccounts();

			request.getSession().setAttribute("targetAccounts", tarAccounts);
			request.setAttribute("successMessage", "Welcome, " + custId);
		} else {
			modelAndView = new ModelAndView("goLogIn");
			request.setAttribute("errorMessage",
					"Invalid loginId or password! Please try again!");
		}

		// modelAndView.addObject("currentCustomer", customer);
		return modelAndView;
	}

	/**
	 * Log out a customer
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/logOutCustomer")
	public String logOut(HttpServletRequest request, Model model) {
		request.getSession().removeAttribute("currentCustomer");
		return "forward:/home";
	}

	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception ex) {

		ModelAndView model = new ModelAndView("customerList");
		model.addObject("errorMessage", "Exception occurred");

		return model;
	}

}
